package com.rainwen.shiro.service;

import com.rainwen.shiro.entity.SysRole;
import com.rainwen.shiro.entity.SysRoleResourceExample;
import com.rainwen.shiro.mapper.SysRoleMapper;
import com.rainwen.shiro.mapper.SysRoleResourceMapper;
import com.rainwen.shiro.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author rain.wen
 * @date 2017/8/9
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleResourceMapper sysRoleResourceMapper;

    public List<SysRole> findRoles(PageRequest pageRequest) {
        return sysRoleMapper.findRoles(pageRequest);
    }

    /**
     * 创建角色
     *
     * @param role
     * @return
     */
    public SysRole addSysRole(SysRole role) {
        sysRoleMapper.insertSelective(role);
        return role;
    }

    /**
     * 更新角色
     *
     * @param role
     * @return
     */
    public SysRole updateSysRole(SysRole role) {
        sysRoleMapper.updateByPrimaryKeySelective(role);
        return role;
    }

    /**
     * 删除角色
     *
     * @param roleId
     */
    public void deleteById(Integer roleId) {
        sysRoleMapper.deleteByPrimaryKey(roleId);
        deleteRoleResource(roleId);
    }

    /**
     * 删除所有角色资源
     *
     * @param roleId
     */
    public void deleteRoleResource(Integer roleId) {
        SysRoleResourceExample example = new SysRoleResourceExample();
        example.createCriteria().andSysRoleIdEqualTo(roleId);
        sysRoleResourceMapper.deleteByExample(example);
    }

    /**
     * 添加角色-资源之间关系
     *
     * @param roleId
     * @param resourceIds
     */
    public int addRoleResource(Integer roleId, List<Integer> resourceIds) {
        //粗暴点删除后再添加
        deleteRoleResource(roleId);

        return sysRoleResourceMapper.batchInsert(roleId, resourceIds);
    }

    /**
     * 移除角色-资源之间关系
     *
     * @param roleId
     * @param resourceIds
     */
    public void deleteRoleResource(Integer roleId, List<Integer> resourceIds) {
        SysRoleResourceExample example = new SysRoleResourceExample();
        example.createCriteria().andSysRoleIdEqualTo(roleId).andSysResourceIdIn(resourceIds);
        sysRoleResourceMapper.deleteByExample(example);
    }
}
